/**
 *上海交大-鹏越惊虹
 */

package org.infosec.lc.exercises.apacheHttpClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**  
 * @Title: LoginKaixin.java
 * @Package org.infosec.lc.exercises.apacheHttpClient.LoginKaixin
 * @Description: TODO
 * @author 林超 
 * @date Dec 4, 2012 11:11:18 AM
 * @version V1.0  
 */
public class LoginKaixin {
	
	public static void main(String[] args) {
		
		HttpClient httpclient = new DefaultHttpClient();
//		HttpGet get = new HttpGet("http://192.168.9.240:8080/shark-webapp");
//		HttpPost post = new HttpPost("http://192.168.9.205");
		HttpPost post = new HttpPost("http://192.168.9.240:8080/shark-webapp/");
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("login_name", "superadmin"));
		formparams.add(new BasicNameValuePair("password", "29e9621671346709e5ba5961a358675f"));
//		formparams.add(new BasicNameValuePair("txtUserName", "hillstone"));
//		formparams.add(new BasicNameValuePair("txtPasswd", "hillstone"));
		try {
			UrlEncodedFormEntity uef = new UrlEncodedFormEntity(formparams,Consts.UTF_8);
			post.setEntity(uef);
//			HttpResponse response = httpclient.execute(get);
			HttpResponse response = httpclient.execute(post);
			
			   // 判断页面返回状态判断是否进行转向抓取新链接
		       int statusCode = response.getStatusLine().getStatusCode();
		       if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
		            (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
		            (statusCode == HttpStatus.SC_SEE_OTHER) ||
		            (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		         // 此处重定向处理   此处还未验证
		         String newUri = response.getLastHeader("Location").getValue();
		         System.out.println(newUri);
		         httpclient = new DefaultHttpClient();
		         post = new HttpPost(newUri);
		         post.setEntity(uef);
		         response = httpclient.execute(post);
		       }
			
			System.out.println(response.getStatusLine());
			HttpEntity entity = response.getEntity();
			
			
			if(entity!=null){
				System.out.println(EntityUtils.toString(entity,Consts.UTF_8));
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			httpclient.getConnectionManager().shutdown();
		}
	}
}
/**Code End*/